package com.imooc.web.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonView;
import com.imooc.dto.User;
import com.imooc.dto.UserQueryCondition;
import com.imooc.exception.UserNotExistException;

import com.imooc.security.core.properties.SecurityProperties;
import io.jsonwebtoken.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private ProviderSignInUtils providerSignInUtils;

  //  @Autowired
  //  private AppSingUpUtils appSingUpUtils;

    @Autowired
    private SecurityProperties securityProperties;
    @GetMapping("/me")
    public Object getCurrentUser(Authentication user, HttpServletRequest request) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException, UnsupportedEncodingException {

        String token = StringUtils.substringAfter(request.getHeader("Authorization"), "bearer ");

        Claims claims = Jwts.parser().setSigningKey(securityProperties.getOauth2().getJwtSigningKey().getBytes("UTF-8"))
                .parseClaimsJws(token).getBody();

        String company = (String) claims.get("company");

        System.out.println(company);

        return user;
    }
    @PostMapping("/regist")
    public void regist(User user, HttpServletRequest request){
        // 不管是注册用户,还是绑定用户,都会拿到一个用户唯一标识

        String userId = user.getUsername();
       // providerSignInUtils.doPostSignUp(userId,new ServletWebRequest(request));
      //  appSingUpUtils.doPostSignUp(new ServletWebRequest(request),userId);

    }


    @RequestMapping()
    @JsonView(User.UserSimpleView.class)
    @ApiOperation(value = "用户查询服务")
    public Object query(UserQueryCondition user){
        System.out.println(JSON.toJSONString(user));

        List<User> users = Arrays.asList(new User(), new User(), new User());

        return users;
    }

    @GetMapping("/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public Object getInfo( @ApiParam("用户id") @PathVariable String id){
        System.out.println("进入 getInfo");
      //  throw new UserNotExistException(id);
      //  throw new RuntimeException("自定义异常");
       User user = new User();
        user.setUsername("zhangsan");
        return user;

    }

    @PostMapping
    //@ApiOperation(value = "创建用户")
    @SuppressWarnings("all")
    public User create(@Valid @RequestBody User user, BindingResult errors) {
        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(error->{
                System.out.println(error.getDefaultMessage());
            });
        }

        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getBirthday());

        user.setId("1");
        return user;
    }


    @PutMapping("/{id:\\d+}")
    @SuppressWarnings("all")
    public User update(@Valid @RequestBody User user ,BindingResult errors){
        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(error->{
                System.out.println(error.getDefaultMessage());
            });
        }
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getBirthday());

        user.setId("1");
        return user;
    }

    @DeleteMapping("/{id:\\d+}")
    public void delete(@PathVariable String id) {
        System.out.println(id);
    }

    /* @GetMapping("/me")
    public Object me(Authentication authentication){

        return authentication;
        //return SecurityContextHolder.getContext().getAuthentication();
    }*/

    /*@GetMapping("/me")
    public Object me(@AuthenticationPrincipal UserDetails user){

        return user;
        //return SecurityContextHolder.getContext().getAuthentication();
    }
*/
}
